define(['wiseMen/dataModel/QueryDefTpl','wiseMen/dataModel/FormControls','wiseMen/dataModel/FormColumnViewModel'],function(QueryDefTpl,Control,FormColumnViewModel){
	webUtils.nameSpace("FormBuilder");
	
	FormBuilder.DataModel=function(formBuilder,param){
		var ctrs=[];
		var ctrsMap={};
		var dataModelDef;
		
		this.init=function(){
			param=$.extend({
				readOnly:false,
				loadSubModelAble:true
			},param);
			dataModelDef=formBuilder.getDataModelDefInfo(param);
			this.initView();
		};
		this.getDataModelDef=function(){
			return dataModelDef;
		};
		this.initView=function(){
			var ctrsViews=formBuilder.buildFormView(dataModelDef,param);
			this.appendCtrs(ctrsViews);
		};
		this.initData=function(){
			var me=this;
			var id=param.paramDatas["ID"];
			if(id){
				$.ajax({
					url:ctx+"/formDataAction/findById.do",
					data:{code:dataModelDef.code,id:id},
					dataType:"json",
					async:false,
					success:function(datas){
						$.extend(datas,param.paramDatas);
						if(datas){
							me.setData(datas);
						}else{
							webUtils.error("加载数据失败");
						}
					},
					error:function(){
						webUtils.error("加载数据失败");
					}
				});
			}else{
				me.setData(param.paramDatas);
			}
		};
		
		this.setData=function(data){
			var me=this;
			$.each(data,function(i,n){
				me.setCtrVal(i,n,data);
			});
		}
		this.collectDatas=function(){
			var fields={};
			$.each(ctrs,function(i,n){
				if(!n.isReadOnly()){
					fields[n.getFieldCode()]=n.getValue();
				}
			})
			return {
				code:dataModelDef.code,
				fields:fields
			};
		};
		this.appendCtrs=function(ctrsR){
			$.each(ctrsR,function(i,n){
				ctrs.push(n);
				var key=n.getFieldCode().toUpperCase();
				ctrsMap[key]=n;
			})
		};
		this.getCtr=function(fieldName){
			var key=fieldName.toUpperCase();
			return ctrsMap[key];
		};
		this.setCtrVal=function(fieldName,val,datas){
			var ctr=this.getCtr(fieldName);
			if(ctr){
				ctr.setValue(val,datas);
			}
		};
		
		this.init();
	}
	
	FormBuilder.main=function(config){
		var me=this;
		
		var dataModels=[];
		var dataModelMap={};
		
		var subTables=[];
		var gridTables=[];
		
		this.formViewDom=null;
		this.config=null;
		
		this.init=function(cfg){
			this.initConfigInfo(cfg);
			this.formViewDom=me.config.formViewDom;
		}
		
		this.build=function(){
			this.initEvent();
			this.initData();
			if(config.extScript){
				var t=eval("(function _t(formBuilder){"+config.extScript+"(formBuilder);})");
				var v=t.call(null,this);
			}
			webUtils.topicPublish("form.afterBuild",this,true);
			return this;
		}
		this.setData=function(params){
			$.each(params,function(i,n){
				getDataModel(i).setData(n);
			});
		}
		this.addDataModel=function(params){
			var dataModel=new FormBuilder.DataModel(this,params);
			pushDataModel(dataModel);
			return dataModel;
		}
		var pushDataModel=function(dataModel){
			dataModels.push(dataModel);
			dataModelMap[dataModel.getDataModelDef().code.toUpperCase()]=dataModel;
		}
		var getDataModel=function(dataModelCode){
			return dataModelMap[dataModelCode.toUpperCase()];
		}
		this.addSubModel=function(ctr){
			if(me.config.subModelViewDom){
				var nav=me.config.subModelViewDom.find(".nav");
				var tabContent=me.config.subModelViewDom.find(".tab-content");
				nav.append('<li><a href="#'+ctr.getFieldCode()+'" >'+ctr.getFieldName()+'</a></li>');
				var v=ctr.getViewObj();
				var w=$('<div role="tabpanel" class="tab-pane" id="'+ctr.getFieldCode()+'"></div>').append(v);
				tabContent.append(w);
				ctr.afterAppend();
			}
		} 
		this.initData=function(){
			$.each(dataModels,function(i,n){
				n.initData();
			});
		}
		this.initEvent=function(){
			me.formViewDom.validation();
			if(me.config.submitBtDom){
				
				me.config.submitBtDom.click(function(){
					if(!me.config.submitLock){
						me.config.submitLock=true;
						me.config.submitBtDom.attr('disabled',"true");
						me.submitDatas(function(result){
							me.config.submitBtDom.removeAttr('disabled');
						});
						setTimeout(function(){
							me.config.submitLock=false;
						},2000);
					}
				});
			}
		}
		
		this.initConfigInfo=function(cfg){
			this.config=$.extend({},FormBuilder.defaultConfig,cfg);
			if(!this.config.uuid){
				this.config.uuid=webUtils.uuid();
			}
			this.config.submitLock=false;
		}
		
		this.buildFormView=function(dataModelDef,param){
			var fields=dataModelDef.fields;
			
			var ctrs=[];
			var subModels=[];
			var formColumnViewModel=new FormColumnViewModel({
				type:me.config.columnView,
				formViewDom:me.formViewDom
			});
			//添加其他可见结构
			$.each(fields,function(i,n){
				
				var currentCol;
				var ctr=Control.factory({
					builder:me,
					field:n,
					dataModelDef:dataModelDef,
					readOnly:param.readOnly
				});
				
				if(ctr){
					if(!ctr.isHiddenField && n.controlType!="subModel"){
						ctrs.push(ctr);
						
						formColumnViewModel.append(ctr);
						
					}else if(n.controlType=="subModel" && param.loadSubModelAble){
						ctrs.push(ctr);
						me.addSubModel(ctr);
					}else if(ctr.isHiddenField){
						ctrs.push(ctr);
						var currentCtr=ctr.getViewObj();
						me.formViewDom.prepend(currentCtr);
						ctr.afterAppend();
					}
				}
			});
			
			if(me.config.subModelViewDom){
				me.config.subModelViewDom.tab();
				me.config.subModelViewDom.find(".nav a:first").tab("show");
			}
			return ctrs;
		};
		this.appendHiddenField=function(params){
			var ctr=Control.factory({
				builder:me,
				field:{
					controlType:'hidden',
					originalName:params.originalName
				},
				table:params.table
			});
			var currentCtr=ctr.getViewObj();
			me.formViewDom.prepend(currentCtr);
			ctr.afterAppend();
			return ctr;
		}
		this.collectDatas=function(){
			var datas={datas:[]};
			$.each(dataModels,function(i,dataModel){
				d=dataModel.collectDatas();
				datas.datas.push(d);
			});
			return datas;
		}
		this.beforeSubmit=function(){
			if(!me.formViewDom.valid()){
				return false;
			}else{
				return true;
			}
		}
		this.submitDatas=function(callback){
			var datas=me.collectDatas();
			if(this.beforeSubmit()){
				if(this.config.side=='server'){
					var postDataStr=JSON.stringify(datas);
					var postDataStrBase64=Base64.encode(postDataStr);
					$.post(ctx+"/formDataAction/submit.do",{data:postDataStrBase64},function(result){
						webUtils.alert(result.msg);
						if(callback){
							callback.call(me,result);
						}
						if(result.success){
							if(me.config.onSubmitSuccess){
								result.datas=datas;
								me.config.onSubmitSuccess.call(me,result);
							}
						}
					});
				}else{
					me.config.onSubmitSuccess.call(me,{
						datas:datas
					});
				}
			}else{
				callback.call(me,null);
			}
			
		}
		this.destroy=function(){
		}
		
		
		
		this.getDataModelDefInfo=function(params){
			var dataModelDefInfo;
			
			$.ajax({
				url:ctx+"/dataModelDefAct/findStrutsByCode.do",
				async:false,
				data:{code:params.dataModelCode},
				dataType:"json",
				success:function(info){
					if(info){
						dataModelDefInfo=info;
					}else{
						webUtils.error("数据加载失败");
					}
				},
				error:function(){
					webUtils.error("数据加载失败");
				}
			});
			
			return dataModelDefInfo;
		}
		
		this.init(config);
	};
	
	FormBuilder.defaultConfig={
		uuid:null,
		dataId:null,
		formViewDom:null,
		submitBtDom:null,
		subTableViewDom:null,
		columnView:"11"
	};
	
	
	return FormBuilder.main;
});

		
		